package com.czg.jsonschema2lombokpojo.util;

import com.czg.jsonschema2lombokpojo.config.GenerationConfig;

import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JDefinedClass;

public class AnnotationHelper {

    private static final String JAVA_8_GENERATED = "javax.annotation.Generated";
    private static final String JAVA_9_GENERATED = "javax.annotation.processing.Generated";
    private static final String GENERATOR_NAME = "jsonschema2pojo";

    private static boolean tryToAnnotate(JDefinedClass jclass, String annotationClassName) {
        try {
            Class.forName(annotationClassName);
            JClass annotationClass = jclass.owner().ref(annotationClassName);
            JAnnotationUse generated = jclass.annotate(annotationClass);
            generated.param("value", GENERATOR_NAME);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }

    }

    public static void addGeneratedAnnotation(GenerationConfig config, JDefinedClass jclass) {
        if (JavaVersion.is9OrLater(config.getTargetVersion())) {
            tryToAnnotate(jclass, JAVA_9_GENERATED);
        } else {
            tryToAnnotate(jclass, JAVA_8_GENERATED);
        }
    }

}
